//
//  UserAccountViewModel.swift
//  SinaWeibo
//
//  Created by Tony-ztb on 15/12/17.
//  Copyright © 2015年 Tony-ztb. All rights reserved.
//

import UIKit
import AFNetworking

// 封装网络请求和  业务逻辑
class UserAccountViewModel: NSObject {
    
    var userAccount: UserAccount?
    
    override init() {
        userAccount = UserAccount.loadAccount()
        super.init()
    }
    // 判断用户是否已经登陆
    var userLogin: Bool {
        return userAccount?.access_token != nil
    }
    
    // 用户名
    var userName: String? {
        return userAccount?.name
    }
    
    // 用户头像
    var userHeadURL: NSURL? {
        let url = NSURL(string: userAccount?.avatar_large ?? "")
        
        return url
    }
    
    // 用户token
    var token: String? {
        return userAccount?.access_token
    }

    // MARK: 加载用户token(请求标识)
    func loadAccessToken(code: String, finished: (isSuccess: Bool) -> ()) {
        
        // 接口名称
        let urlString = "oauth2/access_token"
        // 参数
        let parameters = ["client_id" : client_id, "client_secret" : client_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
 
        NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            // error为nil
            if error != nil {
                finished(isSuccess: false)
                return
            }
            
            // 代码走到这里说明 dict一定有值
            // 字典转模型
            let userAccount = UserAccount(dict: dict!)
            
            self.loadUserInfo(userAccount, finished: finished)

        }
   
        /*
        // 接口名称
        let urlString = "oauth2/access_token"
        // 参数
        let parameters = ["client_id" : client_id, "client_secret" : client_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        AFN.POST(urlString, parameters: parameters, progress: { (p) -> Void in
            print(p)
            }, success: { (_, result) -> Void in
                print(result)
                
                /*
                {
                "access_token" = "2.00RSOtGGggazgC049b73d688Fn8UFC";
                "expires_in" = 157679999;
                "remind_in" = 157679999;
                uid = 5598617997;
                }
                */
                
                // 获取token成功
                // 获取用户信息
                if let dict = result as? [String : AnyObject] {
                    //                    let token = dict["access_token"] as! String
                    //                    let uid = dict["uid"] as! String
                    //                    self.loadUserInfo(token, uid: uid)
                    
                    let userAccount = UserAccount(dict: dict)
                    self.loadUserInfo(userAccount, finished: finished)
                    
                    print("===\(userAccount)")
                }
                
            }) { (_, error) -> Void in
                print(error)
        }
        */
        
        
        
    }
    
    // MARK: 获取用户信息
    private func loadUserInfo(account: UserAccount, finished: (isSuccess: Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        if let token = account.access_token, uid = account.uid {
            
            let parameters = ["access_token" : token, "uid" : uid]
            
            
            NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters, finished: { (dict, error) -> () in
                if error != nil {
                    // 请求失败
                    finished(isSuccess: false)
                    return
                }
                
                // 请求成功
                // 获取用户信息
                let avatar_large = dict!["avatar_large"] as! String
                let name = dict!["name"] as! String
                
                account.avatar_large = avatar_large
                account.name = name
                // 获取到需要的用户的完整信息
                //                        print(account)
                // 存储自定义对象
                account.saveAccount()
                
                finished(isSuccess: true)
            })
            
        }
        
    }
    
    
}
